package com.ym.medical.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ym.core.exception.BusinessException;
import com.ym.core.utils.tkmybatis.BaseSVImpl;
import com.ym.core.utils.tkmybatis.TK;
import com.ym.medical.dao.AddressListDao;
import com.ym.medical.dao.CommentRecordDao;
import com.ym.medical.dao.PatientDetailDao;
import com.ym.medical.dao.UserCollectionDao;
import com.ym.medical.domain.entity.AddressGroupEntity;
import com.ym.medical.domain.entity.AddressListEntity;
import com.ym.medical.domain.entity.InformationEntity;
import com.ym.medical.domain.entity.PatientDetailEntity;
import com.ym.medical.domain.param.*;
import com.ym.medical.domain.vo.CounsellingRoomRecordVO;
import com.ym.medical.domain.vo.PCMyDoctorVo;
import com.ym.medical.domain.vo.PatientAccountVo;
import com.ym.medical.domain.vo.PatientVo;
import com.ym.medical.enums.*;
import com.ym.medical.service.IAddressGroupSV;
import com.ym.medical.service.IAddressListSV;
import com.ym.medical.service.ICommonSV;
import com.ym.medical.service.IInformationSV;
import com.ym.medical.service.IPatientSV;
import org.apache.poi.ss.formula.constant.ErrorConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author dai
 * @create 2019-05-06 13:04
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class PatientSVImpl extends BaseSVImpl<PatientDetailEntity, PatientDetailDao> implements IPatientSV {
	private static final int PARSE_OK = 1;
	@Autowired
	private CommentRecordDao commentRecordDao;
	@Autowired
	private ICommonSV commonSV;
	@Autowired
	private IAddressListSV addressListSV;
	@Autowired
	private IAddressGroupSV addressGroupSV;

	@Autowired
	private IInformationSV informationSV;

	@Autowired
	private IAddressListSV iAddressListSV;

	@Autowired
	private UserCollectionDao userCollectionDao;

	@Autowired
	private AddressListDao addressListDao;

	@Override
	public boolean insertEvalDoctor(CommentRecordParam commentRecordModel) {

		/*保存评价*/
		CommentRecordParam recordModel = new CommentRecordParam();
		recordModel.setOrderId(commentRecordModel.getOrderId());
		if(!commentRecordDao.select(recordModel.covert()).isEmpty()){
			throw new BusinessException("已经评价了喔");
		}
		int flag = commentRecordDao.insertSelective(commentRecordModel.covert());
		if (flag != PARSE_OK) {
			return false;
		}
		/*关联标签*/
		List<PatientRateTagParam> patientRateTagVos = commentRecordModel.getPatientRateTagVos();
		if (patientRateTagVos != null && !patientRateTagVos.isEmpty()) {
			for (PatientRateTagParam model : patientRateTagVos) {
				if (model != null) {
					String sql = "insert into user_taglibrary (order_id,taged_user_id,tag_user_id,tag_id,tag_type) " +
							"values(" + commentRecordModel.getOrderId() + "," + commentRecordModel.getCommentAppperson() + "," + commentRecordModel.getCommentPerson() + ",#{model.id},#{model.tglbType})";
					commonSV.insertEntity(sql, model);
				}
			}

			//更改消息表中的订单为已评价
			InformationParam model = new InformationParam();
			model.setInforType(InformationInforTypeEnum.INQUIRY.getKey());
			model.setReceiverObjId(commentRecordModel.getCommentPerson());
			List<InformationEntity> informationList = informationSV.selectList(model.covert());
			for (InformationEntity information : informationList) {
				CounsellingRoomRecordVO counsellingRoomRecordVO =  JSONObject.parseObject(information.getExtContent(),CounsellingRoomRecordVO.class);
				//修改消息为已评价
				if(commentRecordModel.getOrderId().equals(counsellingRoomRecordVO.getId())){
					counsellingRoomRecordVO.setCrId(commentRecordModel.getId());
					information.setExtContent(JSONObject.toJSONString(counsellingRoomRecordVO, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat));
					informationSV.updateById(information);
				}
			}
			return true;
		}
		return false;
	}


	/**
	 * 添加关注 成为医生的粉丝
	 *
	 * @param patientId
	 * @param doctorId
	 * @return
	 */
	@Override
	public Long addAttention(Long patientId, long doctorId) {
		//查询通讯录分组表
		AddressGroupEntity addressGroup = null;
		//查询粉丝分组
		AddressGroupParam addressGroupModel = new AddressGroupParam();
		addressGroupModel.setAlgIdent(AddressGroupAlgIdentEnum.IN_PATIENTS_WITH.getKey());
		addressGroupModel.setAlgType(AddressGroupAlgTypeEnum.System.getKey());
		addressGroupModel.setAlgName(SystemGroupEnum.PATIENT.FANS.getName());
		addressGroupModel.setUserId(doctorId);
		List<AddressGroupEntity> addressGroups = addressGroupSV.selectList(addressGroupModel.covert());
		if (addressGroups != null && !addressGroups.isEmpty()) {
			addressGroup = addressGroups.get(0);
		}
		//判断是否已经关注
		Long groupId = addressGroup.getId();
		AddressListParam listModel = AddressListParam.builder()
				.algId(groupId).userId(patientId).idType(AddressListIdTypeEnum.THE_USER.getKey()).build();
		AddressListEntity addressList = iAddressListSV.selectOne(listModel.covert());
		if (addressList != null){
			throw new BusinessException("不能重复关注");
		}
		//粉丝添加
		return addressListSV.addFriend(patientId, doctorId, AddressListIdTypeEnum.THE_USER.getKey(), addressGroup == null ? null : addressGroup.getId());
	}

	/**
	 * 取消关注
	 *
	 * @param id
	 * @return
	 */
	@Override
	public int cancelAttention(long id) {
		return addressListSV.cancelAttention(id);
	}

	/**
	 * 患者信息列表
	 *
	 * @param pageNo             页码
	 * @param limit              每页数量
	 * @param patientDetailModel 扩展对象信息
	 * @return
	 */
	@Override
	public PageInfo<PatientVo> getPatientList(int pageNo, int limit, PatientDetailParam patientDetailModel) {

		PageHelper.startPage(pageNo, limit);
		List<PatientVo> patientDetailList = mapper.getPatients(patientDetailModel);
		PageInfo<PatientVo> patientDetailPageInfo = new PageInfo<>(patientDetailList);
		return patientDetailPageInfo;
	}


	/**
	 * 患者账户列表
	 * @param pageNo
	 * @param limit
	 * @param phoneNo
	 * @param realName
	 * @return
	 */
	@Override
	public PageInfo<PatientAccountVo> getAccountList(int pageNo, int limit, String phoneNo, String realName) {
		PageHelper.startPage(pageNo,limit);
		List<PatientAccountVo> accountVos = mapper.getAccountList(phoneNo,realName);
		return new PageInfo<>(accountVos);
	}

	/***
	 * 患者家人列表
	 * @param pageNo
	 * @param limit
	 * @param patientDetailModel
	 * @return
	 */
	@Override
	public PageInfo<PatientDetailEntity> getFamily(int pageNo, int limit, PatientDetailParam patientDetailModel) {
		PageHelper.startPage(pageNo, limit);
		List<PatientDetailEntity> patientFamilyVos = mapper.getFamily(patientDetailModel);
		PageInfo<PatientDetailEntity> patientFamilyVoPageInfo = new PageInfo<>(patientFamilyVos);
		return patientFamilyVoPageInfo;
	}
	/***
	 *
	 * @param pageNo
	 * @param limit
	 * @param userId 用户id
	 * @return
	 */
	@Override
	public PageInfo<PCMyDoctorVo> getPatientDoctor(int pageNo, int limit, Long userId) {
		PageHelper.startPage(pageNo, limit);
		List<PCMyDoctorVo> myDoctorVos = mapper.getPatientDoctor(userId);
		return new PageInfo<>(myDoctorVos);
	}

	/***
	 * 关注话题数量
	 * @param userId
	 * @return
	 */
	@Override
	public int selectTopicTotal(Long userId) {
		int total = userCollectionDao.selectTopicTotal(userId);
		return total;
	}
	/***
	 * 文章数量
	 * @param userId
	 * @return
	 */
	@Override
	public int selectArticleTotal(Long userId) {
		int total = userCollectionDao.selectArticleTotal(userId);
		return total;
	}
	/***
	 * 我的关注医生
	 * @param addressListModel
	 * @param userId
	 * @return
	 */
	@Override
	public PageInfo<PCMyDoctorVo> getFocusCollection(int pageNo, int limit, AddressListParam addressListModel, Long userId) {
		PageHelper.startPage(pageNo, limit);
		List<PCMyDoctorVo> pcMyDoctorVos = addressListDao.getFocusCollection(
				addressListModel,
				userId,
				SystemGroupEnum.PATIENT.FANS.getName());
		return new PageInfo<>(pcMyDoctorVos);
	}
	/**
	 * 家人新增
	 * @param patientDetail
	 * @return
	 */
	@Override
	public int addPatient(PatientDetailEntity patientDetail) {
		if (null == patientDetail.getUserId()){
			throw new BusinessException("userId 为 null !!!");
		}
		Long userId = patientDetail.getUserId();
		if (patientDetail.getIdNo() != null && !"".equals(patientDetail.getIdNo())){
			String idNO = patientDetail.getIdNo();
			PatientDetailEntity p = mapper
					.selectOneByExample(PatientDetailEntity.builder().userId(userId).idNo(idNO).build());
			if (p != null) {
				throw new BusinessException("身份证号已存在");
			}
		}

		//查询是否有本人关系存在
		if (PatientDetailRelationEnum.I_AM.getKey().equals(patientDetail.getRelation())){
			PatientDetailEntity p2 = mapper.selectOneByExample(PatientDetailEntity.builder()
					.relation(PatientDetailRelationEnum.I_AM.getKey()).userId(userId).build());
			if (p2 != null) {
				throw new BusinessException("请选择其他亲属关系");
			}
		}

		patientDetail.setCreateTime(new Date());
		patientDetail.setUpdateTime(new Date());
		patientDetail.setDeleted("00");
		int rows = mapper.insertSelective(patientDetail);
		return rows;
	}
	/**
	 * 家人信息更改
	 * @param patientDetail
	 * @return
	 */
	@Override
	public int upPatient(PatientDetailEntity patientDetail) {
		//查询是否已经存在,身份证信息校验
		String idNO = null;
		Long patientId = patientDetail.getId();
		if (patientDetail.getIdNo() != null && !"".equals(patientDetail.getIdNo())){
			idNO = patientDetail.getIdNo();
			PatientDetailEntity p = mapper.selectOneByExample(
					TK.selectWhere(PatientDetailEntity.class)
					.andEqualTo(PatientDetailEntity::getUserId,patientDetail.getUserId())
					.andNotEqualTo(PatientDetailEntity::getId,patientId)
					.andEqualTo(PatientDetailEntity::getIdNo,idNO).end()
					
			);
			if (p != null) {
				throw new BusinessException("身份证号已存在");
			}
		}

		//查询是否有本人关系存在
		if (PatientDetailRelationEnum.I_AM.getKey().equals(patientDetail.getRelation())){
			PatientDetailEntity p2 = mapper.selectOneByExample(
					TK.selectWhere(PatientDetailEntity.class)
					.andEqualTo(PatientDetailEntity::getUserId,patientDetail.getUserId())
					.andEqualTo(PatientDetailEntity::getRelation,"01")
					.andEqualTo(PatientDetailEntity::getId,patientId)

			);
			if (p2 != null) {
				throw new BusinessException("请选择其他亲属关系");
			}
		}
		patientDetail.setUpdateTime(new Date());
		int rows = mapper.updateByPrimaryKeySelective(patientDetail);
		return rows;
	}

}
